package io.github.bloquesoft.entity.clazz.value;

import io.github.bloquesoft.entity.clazz.AbstractClassPropertyDefinition;
import io.github.bloquesoft.entity.value.PropertyValue;
import lombok.AllArgsConstructor;

import java.lang.reflect.Field;

@AllArgsConstructor
public class AbstractPropertyValue implements PropertyValue {

    private final ObjectEntityValue parent;

    private final AbstractClassPropertyDefinition propertyDefinition;

    @Override
    public String getPropertyId() {
        return propertyDefinition.getId();
    }

    @Override
    public Object getValue() {
        if (!this.parent.isNullValue()) {
            Field field = this.propertyDefinition.getField();
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            try {
                return field.get(this.parent.getValue());
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    @Override
    public Boolean isNullValue() {
        return this.getValue() == null;
    }
}
